package com.banciyuan.bcywebview.biz.detail.tags;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.DailyApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.detail.adapter.DetailConstants;
import com.banciyuan.bcywebview.biz.groupdetail.AutoComplateAdapter;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateHelper;
import com.banciyuan.bcywebview.biz.post.auto.IGetAutoComplate;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.PostCore;
import de.greenrobot.daoexample.model.TagDetail;

/**
 * Created by squall on 2016/1/5.
 */
public class EditDetailTagsActivity extends BaseActivity implements View.OnClickListener {

    private List<TagDetail> tags = new ArrayList<>();
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private RelativeLayout ll_work;
    private RelativeLayout rl_recommend;
    private FlowView tags_area;
    private EditText et_tags;
    private TextView tv_add;
    private TextView acgNotConfirmBtn;
    private TextView acgConfirmBtn;
    private AutoCompleteTextView auto_text;
    private int type;
    private String id;
    private String ud_id;
    private LinkedList<String> mMemoryTagList;
    private RequestQueue queue;
    private String mMemoryTagKey;
    private int maxTagSize = 5;
    private String tagOverSizeHint = "";
    private String work;
    private List<String> characters;
    private String workType;
    private List<String> slist = new ArrayList<>();
    private boolean show_flag = false;
    private AutoComplateAdapter adapter;
    private PostCore newPostCore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_group);
        initArgs();
        initActionbar();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(this);
        Intent intent = getIntent();
        tags = (List<TagDetail>) intent.getSerializableExtra("tags");
        type = intent.getIntExtra("type", 0);
        id = intent.getStringExtra("id");
        ud_id = intent.getStringExtra("ud_id");
        work = intent.getStringExtra("work");
        characters = intent.getStringArrayListExtra("character");
        workType = intent.getStringExtra("worktype");
        initMemoryTagParams();
        getTagFromDiskMemory();
    }

    private void initMemoryTagParams() {
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                mMemoryTagKey = SPConstant.COSTAG;
                maxTagSize = 5;
                tagOverSizeHint = getString(R.string.label_five_limit);
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                mMemoryTagKey = SPConstant.ILLUSTTAG;
                maxTagSize = 5;
                tagOverSizeHint = getString(R.string.label_five_limit);
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                mMemoryTagKey = SPConstant.WRITETAG;
                maxTagSize = 5;
                tagOverSizeHint = getString(R.string.label_five_limit);
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                mMemoryTagKey = SPConstant.DAILYTAG;
                maxTagSize = 3;
                tagOverSizeHint = getString(R.string.label_three_limit);
                break;
        }
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.edittag));
        mActionbarHelper.setActionCallbacks(new ActionbarHelper.OnActionCallbacks() {
            @Override
            public void onBackClick() {
                setBackResultData();
                hideSoftKeyboard();
                finish();
            }

            @Override
            public void onActionClick(int id) {

            }
        });
    }

    @Override
    protected void initUi() {
        ll_work = (RelativeLayout) findViewById(R.id.linearLayout);
        rl_recommend = (RelativeLayout) findViewById(R.id.rl_recommend);
        tags_area = (FlowView) findViewById(R.id.add_tag_lv);
        et_tags = (EditText) findViewById(R.id.tag_add_et);
        tv_add = (TextView) findViewById(R.id.tag_group_add);
        acgNotConfirmBtn = (TextView) findViewById(R.id.acg_group_save_vaild);
        acgConfirmBtn = (TextView) findViewById(R.id.acg_group_save);
        auto_text = (AutoCompleteTextView) findViewById(R.id.edit_group_autotv);
        rl_recommend.setVisibility(View.GONE);
        tags_area.removeAllViews();
        if (!tags.isEmpty()) {
            tags_area.setVisibility(View.VISIBLE);
            for (TagDetail t : tags) {
                addTagView(t);
            }
        }
        if (!TextUtils.isEmpty(work)) {
            auto_text.setText(work);
        }
        ll_work.setVisibility(showWorkLayout() ? View.VISIBLE : View.GONE);
    }

    private boolean showWorkLayout() {
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_DAILY:
            case TimelineFactory.TIMELINE_TYPE_COSER:
                return true;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                return "fanart".equals(workType);
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                return "fanfic".equals(workType);
            default:
                return false;
        }
    }

    @Override
    protected void initAction() {
        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                beginAdd();
            }
        });

        et_tags.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    beginAdd();
                }
                return true;
            }
        });
        auto_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                show_flag = hasFocus;
            }
        });
        final IGetAutoComplate iGetAutoComplate = new IGetAutoComplate() {
            @Override
            public void getComplateList(String s, boolean show) {
                dealJson(s);
            }
        };

        auto_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString())) {
                    auto_text.dismissDropDown();
                    if (type == TimelineFactory.TIMELINE_TYPE_DAILY) {
                        acgNotConfirmBtn.setVisibility(View.GONE);
                        acgConfirmBtn.setVisibility(View.VISIBLE);
                    } else {
                        acgNotConfirmBtn.setVisibility(View.VISIBLE);
                        acgConfirmBtn.setVisibility(View.GONE);
                    }
                } else {
                    getCompleteWork(editable, iGetAutoComplate);
                    acgNotConfirmBtn.setVisibility(View.GONE);
                    acgConfirmBtn.setVisibility(View.VISIBLE);
                }
            }
        });
        auto_text.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                et_tags.requestFocus();
            }
        });
        acgConfirmBtn.setOnClickListener(this);
    }

    private void getCompleteWork(Editable editable, IGetAutoComplate iGetAutoComplate) {
        String url;
        String completeType;
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.getComplete();
                completeType = "work";
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.getComplete();
                completeType = "work";
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.getComplete();
                completeType = "work";
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + CoreApi.getGetcorelist();
                completeType = "";
                break;
            default:
                return;
        }
        AutoComplateHelper autoHelper = new AutoComplateHelper(EditDetailTagsActivity.this, iGetAutoComplate, completeType);
        autoHelper.findServerTitle(editable, true, url);
    }

    private void dealJson(String s) {
        if (StatusCodeUtils.dealStatusCode(s, this)) {
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                slist.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    slist.add(jsonArray.getString(i));
                }
                adapter = new AutoComplateAdapter(slist, this, auto_text.getText().toString());
                auto_text.setAdapter(adapter);
            } catch (Exception e) {

            }
        }
        if (show_flag) {
            auto_text.showDropDown();
        }
    }

    private void beginAdd() {
        String name = et_tags.getText().toString().trim();
        if (TextUtils.isEmpty(name))
            return;
        int i = 0;
        for (; i < tags.size(); i++) {
            if (name.equals(tags.get(i).getTag_name())) {
                break;
            }
        }
        if (i >= tags.size()) {
            if (tags.size() < maxTagSize) {
                if (name.equals(work)) {
                    MyToast.show(EditDetailTagsActivity.this, getString(R.string.tag_work_cannot_repeat));
                    return;
                }
                for (String character : characters) {
                    if (name.equals(character)) {
                        MyToast.show(EditDetailTagsActivity.this, getString(R.string.tag_role_cannot_repeat));
                        return;
                    }
                }
                addTag(name);
            } else
                MyToast.show(this, tagOverSizeHint);
        } else {
            MyToast.show(EditDetailTagsActivity.this, getString(R.string.label_mutli_disable));
        }
    }

    private void addTagView(final TagDetail tagdetail) {
        if (tags_area.getVisibility() == View.GONE) tags_area.setVisibility(View.VISIBLE);
        final View tag = View.inflate(EditDetailTagsActivity.this, R.layout.tag_blue_cancel, null);
        TextView tv_name = (TextView) tag.findViewById(R.id.single_tag_cancel);
        tv_name.setText(tagdetail.getTag_name());
        tag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeTag(tagdetail);

            }
        });
        tags_area.addView(tag);
    }

    private void removeTag(final TagDetail tagDetail) {
        String url = "";
        List<BcyPair> params = new ArrayList<BcyPair>();
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.getDeletetag();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.getDeletetag();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.getDeletetag();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + DailyApi.getDeletetag();
                params.add(new BcyPair(HttpUtils.UDID, ud_id));
                break;
            default:
                return;
        }
        params.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(EditDetailTagsActivity.this).getToken()));
        params.add(new BcyPair(HttpUtils.TAG_ID, tagDetail.getTag_id()));
        params.add(new BcyPair(HttpUtils.TAG_NAMED, tagDetail.getTag_name()));

        Map<String, String> map = HttpUtils.getData(params);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EditDetailTagsActivity.this)) {
                    tags.remove(tagDetail);
                    for (int i = 0; i < tags_area.getChildCount(); i++) {
                        View view = tags_area.getChildAt(i);
                        TextView tv = (TextView) view.findViewById(R.id.single_tag_cancel);
                        if (tv.getText().toString().equals(tagDetail.getTag_name())) {
                            tags_area.removeView(view);
                            break;
                        }
                    }
                    if (tags_area.getChildCount() == 0) {
                        tags_area.setVisibility(View.GONE);
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                MyToast.show(EditDetailTagsActivity.this, getString(R.string.operation_fail));
            }
        };
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(stringRequestParam);
    }

    private void addTag(String name) {
        if (TextUtils.isEmpty(name))
            return;
        String url = "";
        List<BcyPair> params = new ArrayList<BcyPair>();
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.getAddtag();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.getAddtag();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.getAddtag();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + DailyApi.getAddtag();
                params.add(new BcyPair(HttpUtils.UDID, ud_id));
                break;
            default:
                return;
        }
        params.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(EditDetailTagsActivity.this).getToken()));
        params.add(new BcyPair(HttpUtils.TAG_NAMED, name));
        Map<String, String> map = HttpUtils.getData(params);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EditDetailTagsActivity.this)) {
                    try {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        TagDetail td = gson.fromJson(result.toString(), new TypeToken<TagDetail>() {
                        }.getType());
                        tags.add(td);
                        addTagView(td);
                        saveTagInDiskMemory(td.getTag_name());
                        et_tags.setText("");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                MyToast.show(EditDetailTagsActivity.this, getString(R.string.operation_fail));
            }
        };
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(stringRequestParam);
    }


    private void getTagFromDiskMemory() {
        Gson gson = new Gson();
        String tagStrOriginal = SPHelper.getString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), mMemoryTagKey, "[]");
        mMemoryTagList = gson.fromJson(tagStrOriginal, new TypeToken<LinkedList<String>>() {
        }.getType());
    }

    private void saveTagInDiskMemory(String tagName) {
        Gson gson = new Gson();
        mMemoryTagList.addFirst(tagName);
        if (mMemoryTagList.size() > 10) {
            mMemoryTagList.removeLast();
        }
        String tagStr = gson.toJson(new LinkedHashSet<>(mMemoryTagList));
        SPHelper.putString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), mMemoryTagKey, tagStr);
    }

    public void hideSoftKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputManager && inputManager.isActive()) {
            inputManager.hideSoftInputFromWindow(et_tags.getApplicationWindowToken(), 0);
        }
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(work)) {
            acgConfirmBtn.setVisibility(View.GONE);
            acgNotConfirmBtn.setVisibility(View.VISIBLE);
        } else {
            acgConfirmBtn.setVisibility(View.VISIBLE);
            acgNotConfirmBtn.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {
        setBackResultData();
        super.onBackPressed();
    }

    private void setBackResultData() {
        Intent intent = new Intent();
        intent.putExtra("tags", (Serializable) tags);
        intent.putExtra("postcore", newPostCore);
        setResult(DetailConstants.EDIT_TAGS, intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.acg_group_save:
                String tempWork = auto_text.getText().toString();
                modifyWork(tempWork);
                break;
        }
    }

    private void modifyWork(final String updateWork) {
        String url;
        List<BcyPair> params = new ArrayList<>();
        params.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        params.add(new BcyPair(HttpUtils.GROUP_WORK, updateWork));
        switch (type) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                url = HttpUtils.BASE_URL + CoserApi.doUpdatework();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                url = HttpUtils.BASE_URL + IllustApi.doUpdatework();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                url = HttpUtils.BASE_URL + NovelApi.doUpdatework();
                params.add(new BcyPair(HttpUtils.RPID, id));
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                url = HttpUtils.BASE_URL + DailyApi.doUpdatework();
                params.add(new BcyPair(HttpUtils.UDID, ud_id));
                break;
            default:
                return;
        }
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, EditDetailTagsActivity.this)) {
                    MyToast.show(EditDetailTagsActivity.this, getString(R.string.modify_work_succ));
                    work = updateWork;
                    try {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        newPostCore = gson.fromJson(result.toString(), new TypeToken<PostCore>() {
                        }.getType());

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        HashMap<String, String> map = HttpUtils.getData(params);
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                MyToast.show(EditDetailTagsActivity.this, getString(R.string.edit_work_fail));
            }
        };

        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(requestParam);
    }

}
